package com.robot.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.robot.service.langchain.ApiQueryService;
import com.robot.service.langchain.ConversationService;

import dev.langchain4j.model.chat.ChatLanguageModel;

import java.util.HashMap;
import java.util.Map;

/**
 * LangChain服务实现，处理自然语言到API调用的转换
 */
@Service
public class LangChainService {

    private static final Logger logger = LoggerFactory.getLogger(LangChainService.class);

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private ApiQueryService apiQueryService;
    
    @Autowired
    private ConversationService conversationService;
    
    /**
     * 处理自然语言查询并调用相应API
     */
    public String processQuery(String query) {
        if (query == null || query.trim().isEmpty()) {
            return "查询不能为空";
        }
        
        try {
            // 1. 解析查询，获取API调用信息
            String apiCallInfoJson = apiQueryService.parseQuery(query);
            logger.info("API调用信息: {}", apiCallInfoJson);
            
            // 2. 解析API调用信息JSON
            ApiCallInfo apiCallInfo = parseApiCallInfo(apiCallInfoJson);
            if (apiCallInfo == null) {
                return "无法解析您的查询为有效的API调用";
            }
            
            // 3. 执行API调用
            String apiResult = executeApiCall(apiCallInfo);
            logger.info("API调用结果: {}", apiResult);
            
            // 4. 将API结果转换为自然语言
            String naturalLanguageResult = apiQueryService.formatResult(
                query, apiCallInfo.getApiName(), apiResult);
            logger.info("API组装自然语言结果: {}", apiResult);
            return naturalLanguageResult;
        } catch (Exception e) {
            logger.error("处理查询时出错", e);
            return "无法处理您的查询，请稍后重试";
        }
    }
    
    /**
     * 解析API调用信息JSON
     */
    private ApiCallInfo parseApiCallInfo(String apiCallInfoJson) {
        try {
            // 清理JSON字符串，移除可能存在的前后缀
            String cleanedJson = apiCallInfoJson.trim();
            // 移除可能的Markdown代码块标记
            if (cleanedJson.startsWith("```json")) {
                cleanedJson = cleanedJson.substring("```json".length());
            } else if (cleanedJson.startsWith("```")) {
                cleanedJson = cleanedJson.substring("```".length());
            }
            if (cleanedJson.endsWith("```")) {
                cleanedJson = cleanedJson.substring(0, cleanedJson.lastIndexOf("```"));
            }
            cleanedJson = cleanedJson.trim();
            
            logger.debug("解析API调用信息, 清理后的JSON: {}", cleanedJson);
            return objectMapper.readValue(cleanedJson, ApiCallInfo.class);
        } catch (Exception e) {
            logger.error("解析API调用信息失败", e);
            return null;
        }
    }
    
    /**
     * 执行API调用
     */
    private String executeApiCall(ApiCallInfo apiCallInfo) throws JsonProcessingException {
        String baseUrl = "http://localhost:8080/iff" + apiCallInfo.getPath();
        
        // 构建URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);
        apiCallInfo.getParams().forEach(builder::queryParam);
        
        String url = builder.toUriString();
        logger.info("执行API调用: {}", url);
        
        // 调用API
        String response = restTemplate.getForObject(url, String.class);
        
        // 验证响应是有效的JSON
        objectMapper.readTree(response);
        
        return response;
    }
    
    /**
     * 处理多轮对话，支持上下文记忆
     */
    public String chat(String message) {
        if (message == null || message.trim().isEmpty()) {
            return "消息不能为空";
        }
        
        try {
            return conversationService.chat(message);
        } catch (Exception e) {
            logger.error("聊天处理时出错", e);
            return "聊天处理失败，请稍后重试";
        }
    }
    
    /**
     * API调用信息类
     */
    public static class ApiCallInfo {
        private String apiName;
        private String path;
        private String method;
        private Map<String, String> params = new HashMap<>();
        
        public String getApiName() {
            return apiName;
        }
        
        public void setApiName(String apiName) {
            this.apiName = apiName;
        }
        
        public String getPath() {
            return path;
        }
        
        public void setPath(String path) {
            this.path = path;
        }
        
        public String getMethod() {
            return method;
        }
        
        public void setMethod(String method) {
            this.method = method;
        }
        
        public Map<String, String> getParams() {
            return params;
        }
        
        public void setParams(Map<String, String> params) {
            this.params = params;
        }
    }
} 